<template>
  <div>
    <form @submit.prevent="submitForm">
      <div>
        <label for="address">地址:</label>
        <SelectPay_1 type="address" id="address" v-model="form.address" ></SelectPay_1>
      </div>
      <div>
        <label for="serviceTime">选择服务时间:</label>
        <select id="serviceTime" v-model="form.serviceTime">
          <option value="" disabled selected>请选择时间段</option>
          <option value="9:00-12:00">9:00-12:00</option>
          <option value="12:00-15:00">12:00-15:00</option>
          <option value="15:00-18:00">15:00-18:00</option>
        </select>
      </div>
      <div>
        <label for="password">备注:</label>
        <input type="text" id="remark" v-model="form.remark" />
      </div>
      <button type="submit">提交</button>
    </form>

    <div v-if="submitted">
      <h3>提交的数据:</h3>
      <p>地址: {{ form.address }}</p>
      <p>备注: {{ form.remark }}</p>
    </div>
  </div>
</template>

<script>
import {BASE_URL}  from "@/util/Config.js";

import SelectPay_1 from "@/components/SelectPay_1.vue";
import { useUserStore } from '@/stores/user'; // 根据你的项目路径调整

export default {
  components: {
    SelectPay_1
  },
  setup() {
    const userStore = useUserStore();
    return { userStore };
  },
/*  data() {
    return {
      form: {
        name: '',
        email: '',
        password: '',
        address:''
      },
      submitted: false
    };
  },*/
  data() {
    return {

      serviceData: null,
      order:{
        orderId:'',
        catagoryName:'',
        serviceId:'',
        serviceMainName:'',
        orderStatus:'',
        orderStartMoney:'',
        orderEndMoney:null,
        orderDateTime:'',
        orderStartTime:'',
        orderEndTime:'',
        addressLinkman:'',
        addressPhone:'',
      },
      orderId: null,
      form: {
        address: '',
        remark: '',
        serviceTime: ''
      }
    };
  },
  created() {
    const serviceDataStr = this.$route.query.serviceData;
    if (serviceDataStr) {
      this.serviceData = JSON.parse(serviceDataStr);
      console.log('服务数据:', this.serviceData);
    }
  },
  methods: {
    async submitForm() {
      const id = this.$route.params.id;
      const userId = this.userStore.userInfo.userId;

      // 2. 构造 JSON 数据
      const jsonData = {
        userId: userId,
        serviceId: this.$route.query.id,
        addressId: this.form.address.addressId,
        orderRemark: this.form.remark+"【"+this.form.serviceTime+"】",
        orderStartMoney: this.serviceData.orderStartMoney,
        orderEndMoney: this.serviceData.orderEndMoney,
      };

      try {
        // 3. 发送 POST 请求到后端
        const response = await fetch(BASE_URL + '/addOrders', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(jsonData),
          credentials: 'include'
        });
//orders/{id}
        // 4. 检查响应状态
        if (!response.ok) {
          throw new Error('网络响应异常');
        }
        const result = await response.json();
        this.orderId=result.data.orderId;
        const response1 = await fetch(BASE_URL + '/orders/'+this.orderId, {
          method: 'Get',
          headers: {
            'Content-Type': 'application/json'
          },
          credentials: 'include'
        });
        if (!response1.ok) {
          throw new Error('网络响应异常');
        }
        const result2 = await response1.json();
        this.order=result2.data;


        // 5. 获取响应数据（可选）


        // 4. 发送第二个请求：调起支付
        const payResponse = await fetch(BASE_URL + '/api/alipay/pay', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.order),
          credentials: 'include'
        });

        if (!payResponse.ok) {
          throw new Error('支付请求失败');
        }

        const payResultText = await payResponse.text(); // 获取响应文本

        // 创建一个 div 来容纳返回的表单
        const formContainer = document.createElement('div');
        formContainer.innerHTML = payResultText;
        document.body.appendChild(formContainer);

        // 获取并提交表单
        const form = formContainer.querySelector('form');
        if (form) {
          form.submit(); // 自动跳转支付页面
        } else {
          throw new Error('未找到支付表单');
        }

        // 6. 标记为已提交
        this.submitted = true;

      } catch (error) {
        console.error('请求失败:', error);
        alert('操作失败，请重试');
      }
    }}
};
</script>

<style scoped>form {
  max-width: 300px;
  margin: 0 auto;
}

div {
  margin-bottom: 10px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input {
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

button {
  padding: 10px 15px;
  background-color: #42b883;
  color: white;
  border: none;
  cursor: pointer;
}
.select-wrapper {
  max-width: 300px;
  margin: 20px auto;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

select {
  width: 100%;
  padding: 8px 12px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  height: auto; /* 根据内容自动调整高度 */
}

p {
  margin-top: 10px;
  font-size: 14px;
  color: #333;
}
</style>